﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Model.ParamModel;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class TempProductController : BaseController
    {
        #region 获取列表
        [Description("入库物料列表")]
        [ViewPage]
        public ActionResult tempProductlist(TempProductQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = dbcontext.ADZ_GoodsTemp.Where(t => t.is_del == 0);
            if (queryModel.label_type != -10)
                queryable = queryable.Where(t => t.label_type == queryModel.label_type);
            if (queryModel.up_status != -10)
                queryable = queryable.Where(t => t.status == queryModel.up_status);
            if (!string.IsNullOrWhiteSpace(queryModel.MPN))
                queryable = queryable.Where(t => t.MPN.StartsWith(queryModel.MPN));
            if (queryModel.begTime.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.begTime.Value);
            if (queryModel.endTime.HasValue)
            {
                var endTime = queryModel.endTime.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < endTime);
            }


            //var querylist = queryable.OrderByDescending(t => t.update_time).ToList();

            int rowcounts = queryable.Count();

            var querylist = queryable.OrderByDescending(t => t.update_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            ViewData["AllCount"] = rowcounts;

            List<AddTempProductModel> resultList = new List<AddTempProductModel>();
            foreach (var item in querylist)
            {
                var tempModel = JsonHelper.Deserialize<AddTempProductModel>(item.data_json);
                tempModel.aDZ_GoodsTemp = item;
                resultList.Add(tempModel);
            }

            PagedList<AddTempProductModel> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<AddTempProductModel>(resultList, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("临时压缩包列表")]
        [ViewPage]
        public ActionResult moreTempProductList(MoreTempProductQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = dbcontext.ADZ_GoodsTempZip.Where(t => t.seq_id > 0);
            if (queryModel.up_status != -10)
                queryable = queryable.Where(t => ((int)t.status) == queryModel.up_status);

            if (!string.IsNullOrWhiteSpace(queryModel.Batch))
                queryable = queryable.Where(t => t.batch.StartsWith(queryModel.Batch));

            if (!string.IsNullOrWhiteSpace(queryModel.FileName))
                queryable = queryable.Where(t => t.file_name.StartsWith(queryModel.FileName));

            if (queryModel.begTime != null)
                queryable = queryable.Where(t => t.create_time >= queryModel.begTime);
            if (queryModel.endTime != null)
            {
                var endTime = queryModel.endTime.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < endTime);
            }

            int rowcounts = queryable.Count();

            var resultList = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            ViewData["AllCount"] = rowcounts;


            PagedList<ADZ_GoodsTempZip> pagedlist = null;
            if (resultList != null && resultList.Count != 0)
                pagedlist = new PagedList<ADZ_GoodsTempZip>(resultList, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }
        #endregion

        #region 添加/修改导入数据
        [Description("批量导入库存")]
        [ViewPage]
        public ActionResult addMoreTempProduct()
        {
            return View();
        }
        [Description("批量导入库存")]
        [HttpPost]
        public ActionResult addMoreTempProduct(ADZ_GoodsTempZip paramModel)
        {
            Utils.Trim(paramModel);
            ResponseMsg resMsg = new ResponseMsg();
            Tuple<bool, string> ret = TempProductBiz.Instance.addMoreTempProduct(paramModel);
            resMsg.IsSuccess = ret.Item1;
            resMsg.Message = ret.Item2;

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("添加修改入库物料")]
        [ViewPage]
        public ActionResult addTempProduct(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddTempProductModel paramModel = new AddTempProductModel();
            if (id > 0)
            {
                var aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.FirstOrDefault(t => t.seq_id == id && t.is_del == 0);
                if (aDZ_GoodsTemp != null)
                {
                    paramModel = JsonHelper.Deserialize<AddTempProductModel>(aDZ_GoodsTemp.data_json);
                    paramModel.aDZ_GoodsTemp = aDZ_GoodsTemp;
                    ViewBag.ParamModel = paramModel;
                }
                ViewBag.Title = "修改入库物料";
            }
            else
                ViewBag.Title = "添加入库物料";

            return View(paramModel);
        }

        [Description("添加修改入库物料")]
        [HttpPost]
        public ActionResult addTempProduct(AddTempProductModel paramModel)
        {
            Utils.Trim(paramModel);
            long temp_seq_id = paramModel.aDZ_GoodsTemp.seq_id;
            ResponseMsg resMsg = new ResponseMsg();
            if (!ModelState.IsValid)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            paramModel = paramModel ?? new AddTempProductModel();
            ViewBag.ParamModel = paramModel;

            Tuple<bool, string, ADZ_GoodsTemp> ret = TempProductBiz.Instance.addTempProduct(paramModel);

            resMsg.IsSuccess = ret.Item1;
            resMsg.Message = ret.Item2;

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("库存物料上架")]
        [HttpPost]
        public ActionResult toWithdraw(long id = 0)
        {
            BusinessMsgBiz.Instance.SetManagerMsgConfig(new CurrentUser().user.uid, 110);
            ResponseMsg resMsg = new ResponseMsg();

            Tuple<bool, string> ret = TempProductBiz.Instance.toWithdraw(id);

            resMsg.IsSuccess = ret.Item1;
            resMsg.Message = ret.Item2;

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        [Description("批量库存物料上架")]
        [HttpPost]
        public ActionResult toWithdrawMore(string ids)
        {
            BusinessMsgBiz.Instance.SetManagerMsgConfig(new CurrentUser().user.uid, 110);
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Regex.Split(ids, ",");
            foreach (var item in id_arr)
            {
                long num_id = ConvertHelper.TryPraseInt(item, 0);
                if (num_id > 0)
                {
                    Tuple<bool, string> ret = TempProductBiz.Instance.toWithdraw(num_id);
                    if (!ret.Item1)
                    {
                        strb.Append(ret.Item2);
                    }
                }
            }

            if (strb.Length == 0)
            {
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strb.ToString();
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);

        }


        [Description("删除库存物料")]
        [HttpPost]
        public ActionResult delete(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();

            Tuple<bool, string> ret = TempProductBiz.Instance.Delete(id);

            resMsg.IsSuccess = ret.Item1;
            resMsg.Message = ret.Item2;

            return Json(resMsg, JsonRequestBehavior.AllowGet);

        }

        [Description("删除库存物料")]
        [HttpPost]
        public ActionResult deleteMore(string ids)
        {
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Regex.Split(ids, ",");
            foreach (var item in id_arr)
            {
                long num_id = ConvertHelper.TryPraseInt(item, 0);
                if (num_id > 0)
                {
                    Tuple<bool, string> ret = TempProductBiz.Instance.Delete(num_id);
                    if (!ret.Item1)
                    {
                        strb.Append(ret.Item2);
                    }
                }
                else
                {
                    strb.Append($"id{item}不对，");
                }
            }

            if (strb.Length == 0)
            {
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strb.ToString();
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);

        }

        #endregion

        [Description("删除上传的压缩包")]
        [HttpPost]
        public ActionResult deleteMoreTemp(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var model = dbcontext.ADZ_GoodsTempZip.FirstOrDefault(t => t.seq_id == id);
            if (model == null)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"要删除的数据不存在id[{id}]";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (model.status >= 2)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "已解压入库的请不要删除";
            }
            else
            {
                dbcontext.ADZ_GoodsTempZip.Remove(model);
                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("解压入库")]
        [HttpPost]
        public ActionResult unzipMoreTemp(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var model = dbcontext.ADZ_GoodsTempZip.FirstOrDefault(t => t.seq_id == id);
            if (model == null)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"要解压的数据不存在id[{id}]";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (model.status != 1)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"必须为上传成功的才能解压[{id}]";
            }
            else
            {
                var ret = TempProductBiz.Instance.unZipMoreTempProduct(id);
                if (ret.Item1)
                {
                    model.status = 2;
                    model.unzip_time = DateTime.Now;
                    model.remark = ret.Item2;
                }
                else
                {
                    model.status = 3;
                    model.unzip_time = DateTime.Now;
                    model.remark = ret.Item2;
                }
                dbcontext.SaveChanges();

                resMsg.IsSuccess = ret.Item1;
                resMsg.Message = ret.Item2;
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        #region 供应商上传物料
        [Description("供应商上传物料")]
        [ViewPage]
        public ActionResult SupplierAddMoreTempProduct()
        {
            //获取登录用户名
            string loginName = new CurrentUser().user.loginName;
            //获取是否代理商信息
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
            }
            else
                return Redirect("/Home/Problem/");
            return View();
        }
        [Description("供应商上传物料")]
        [HttpPost]
        public ActionResult SupplierAddMoreTempProduct(ADZ_GoodsTempFileSupplier paramModel)
        {
            Utils.Trim(paramModel);

            string loginName = new CurrentUser().user.loginName;
            //获取是否代理商信息
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                paramModel.supplier_id = managerUser.supplier_id;
            }
            else
                return Redirect("/Home/Problem/");

            ResponseMsg resMsg = new ResponseMsg();
            Tuple<bool, string> ret = TempProductBiz.Instance.SupplieraddMoreTempProduct(paramModel);
            resMsg.IsSuccess = ret.Item1;
            resMsg.Message = ret.Item2;

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        [Description("供应商上传物料列表")]
        [ViewPage]
        public ActionResult SupplierMoreTempProductList(MoreTempProductQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = dbcontext.ADZ_GoodsTempFileSupplier.Where(t => t.seq_id > 0);
            if (queryModel.up_status != -10)
                queryable = queryable.Where(t => ((int)t.status) == queryModel.up_status);

            if (!string.IsNullOrWhiteSpace(queryModel.Batch))
                queryable = queryable.Where(t => t.batch.StartsWith(queryModel.Batch));

            if (!string.IsNullOrWhiteSpace(queryModel.FileName))
                queryable = queryable.Where(t => t.file_name.Contains(queryModel.FileName));

            if (queryModel.begTime != null)
                queryable = queryable.Where(t => t.create_time >= queryModel.begTime);
            if (queryModel.endTime != null)
            {
                var endTime = queryModel.endTime.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < endTime);
            }
            string loginName = new CurrentUser().user.loginName;
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                queryModel.supplier_id = managerUser.supplier_id;
                ViewBag.supplier_id = managerUser.supplier_id;
            }
            if (!string.IsNullOrWhiteSpace(queryModel.supplier_id_name))
            {
                var item = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == queryModel.supplier_id_name);
                if (item == null)
                {
                    return null;
                }
                queryModel.supplier_id = item.supplier_id;
            }

            if (queryModel.supplier_id > 0)
            {
                queryable = queryable.Where(t => t.supplier_id == queryModel.supplier_id);
            }


            int rowcounts = queryable.Count();

            var resultList = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            ViewData["AllCount"] = rowcounts;


            PagedList<ADZ_GoodsTempFileSupplier> pagedlist = null;
            if (resultList != null && resultList.Count != 0)
                pagedlist = new PagedList<ADZ_GoodsTempFileSupplier>(resultList, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }


        [Description("删除供应商上传的表格")]
        [HttpPost]
        public ActionResult deleteSupplierMoreTemp(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            long supplier_id = 0;
            string loginName = new CurrentUser().user.loginName;
            //获取是否代理商信息
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                supplier_id = managerUser.supplier_id;
            }
            else
                return Redirect("/Home/Problem/");

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var model = dbcontext.ADZ_GoodsTempFileSupplier.FirstOrDefault(t => t.seq_id == id && t.supplier_id == supplier_id);
            if (model == null)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"要删除的数据不存在id[{id}]";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (model.status >= 2)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "已入库的请不要删除";
            }
            else
            {
                dbcontext.ADZ_GoodsTempFileSupplier.Remove(model);
                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("标记供应商上传的数据已入库")]
        [HttpPost]
        public ActionResult remarkSupplierMoreTemp(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            string loginName = new CurrentUser().user.loginName;
            //获取是否代理商信息
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                return Redirect("/Home/Problem/");
            }

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var model = dbcontext.ADZ_GoodsTempFileSupplier.FirstOrDefault(t => t.seq_id == id);
            if (model != null)
            {
                model.status = 2;
                model.remark_time = DateTime.Now;
                model.remark = "已入库";
                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

    }
}